import { UserResidenceTime } from "~/api";

export default defineNuxtRouteMiddleware((to, from) => {
    const pageStore = usePageStore();
    const userStore = useUserStore();

    if (to.meta && to.meta.layout) {
        setPageLayout(to.meta.layout);
    } else {
        if (to.path.startsWith("/admin")) {
            setPageLayout("admin");
        } else if (to.path.startsWith("/login") || to.path.startsWith("/register") || to.path.startsWith("/forgetPwd")) {
            setPageLayout("login");
        } else if (to.path.startsWith("/caseView")) {
            setPageLayout("none");
        } else {
            setPageLayout("default");
        }
    }

    if (process.client) {
        if (Object.keys(pageStore.residenceTime).length > 0) {
            // 提交浏览时间

            let residenceTime = pageStore.residenceTime;
            let stayTime = (
                (Date.now() - residenceTime.startTime) /
                1000
            ).toFixed(2);

            UserResidenceTime({
                name: residenceTime.name,
                consumer_id: userStore.userInfo.id || "",
                begin_time: parseInt(residenceTime.startTime / 1000),
                duration_of_stay: stayTime,
            });

            pageStore.residenceTime = {};
        }

        if (to.meta.residence) {
            pageStore.residenceTime = {
                startTime: Date.now(),
                name: to.meta.residenceName,
            };
        } else if (to.path.includes("admin")) {
            pageStore.residenceTime = {
                startTime: Date.now(),
                name: "会员中心",
            };
        }
    }

    pageStore.pageName = to.meta.pageName;
});
